package web

import (
	"GinHelloWorld/db"
	"GinHelloWorld/model"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gomodule/redigo/redis"
	"net/http"
)

/**
校验必须登录
*/
func CheckLogin() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		_, flag := ctx.GetQuery("token")
		if !flag {
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"code":    401,
				"message": "用户名未授权",
			})
			// 路由阻断，很像vertx吧？
			ctx.Abort()
		} else {
			// 向下执行下一个路由
			ctx.Next()
		}
	}
}

func Register(ctx *gin.Context) {
	getDB := db.GetDB()
	//var requestUser model.User
	//_ = ctx.Bind(&requestUser)
	//name := requestUser.Name
	//username := requestUser.Username
	//address := requestUser.Address
	//age := requestUser.Age
	//sex := requestUser.Sex
	user := model.User{}
	_ = ctx.BindJSON(&user)

	if len(user.Username) == 0 {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{
			"code":    422,
			"message": "用户名不能为空",
		})
		return
	}

	// 理解成重新new了一个
	user1 := model.User{}
	getDB.Where("username=?", user.Username).First(&user1)
	if len(user1.Username) != 0 {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{
			"code":    422,
			"message": "用户已存在",
		})
		return
	}

	getDB.Create(&user)
	//返回结果
	ctx.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "注册成功",
	})
}

func SelectUserById(ctx *gin.Context) {
	getDB := db.GetDB()
	username := ctx.Query("username")
	if username == "" {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{
			"code":    422,
			"message": "用户名不能为空",
		})
		return
	}

	var user = model.User{}
	getDB.Where("username=?", username).First(&user)
	//返回结果
	ctx.JSON(http.StatusOK, user)
}

func GetUserQuery(ctx *gin.Context) {
	query := model.UserQuery{}
	err := ctx.BindQuery(&query)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "参数错误",
		})
	} else {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": query,
		})
	}
}

func SaveUsers(ctx *gin.Context) {
	users := model.Users{}
	err := ctx.BindJSON(&users)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": fmt.Sprintf("参数错误: %v", err.Error()),
		})
	} else {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": users,
		})
	}
}

func GetRedisKey(ctx *gin.Context) {
	key, _ := ctx.GetQuery("key")
	fmt.Printf("redis key = %s\n", key)
	conn := db.RedisPool.Get()
	result, err := redis.String(conn.Do("get", key))
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": fmt.Sprintf("参数错误: %v", err.Error()),
		})
	} else {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": fmt.Sprintf("获取到的redis数据为: %s", result),
		})
	}
}

func GetUserDetail(ctx *gin.Context) {
	var userVOS []model.UserVO
	getDB := db.GetDB()
	getDB.Table("user u").Select("u.*, ud.school_name").
		Joins("left join user_detail ud on u.username = ud.username").Where("u.username ").Scan(&userVOS)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": userVOS,
	})
}

func GetUser2Many(ctx *gin.Context) {
	var userVOS []model.UserOne2Many
	getDB := db.GetDB()
	getDB.Table("user_detail").
		Find(&userVOS)
	data := getDB.Table("user").Model(&userVOS).
		Preload("UserDetail").
		Find(&userVOS)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": data,
	})
}
